﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace BasicCMS.Data
{
    public class UpdateBuilder:IPersistentBuilder
    {
        private readonly IUnitOfWork unitOfWork;
        private IList<KeyValuePair<string, object>> paramters = new List<KeyValuePair<string, object>>();
        private IList<KeyValuePair<string, object>> fields = new List<KeyValuePair<string, object>>();
        private string tableName;
        private string condition;
        private IDbCommand command;

        public UpdateBuilder(IUnitOfWork unitOfWork, string tableName)
        {
            this.unitOfWork = unitOfWork;
            this.tableName = tableName;
        }

        public IDbCommand Command
        {
            set { command = value; }
        }

        /// <summary>
        /// 添加参数
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public UpdateBuilder Set(string name, object value)
        {
            fields.Add(new KeyValuePair<string, object>(name, value));
            return this;
        }

        public UpdateBuilder Where(string condition)
        {
            this.condition = condition;
            return this;
        }

        /// <summary>
        /// 添加参数
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public UpdateBuilder Param(string name, object value)
        {
            paramters.Add(new KeyValuePair<string, object>(name, value));
            return this;
        }

        void IPersistentBuilder.Persistent()
        {
            StringBuilder fieldsBuilder = new StringBuilder();
            StringBuilder conditionBuidler = new StringBuilder();
            StringBuilder sqlBuilder = new StringBuilder();

            for(int i=0;i<fields.Count;i++)
            {
                var item = fields[i];
                string paramKey = String.Format("@{0}_{1}", item.Key, i);
                fieldsBuilder.AppendFormat("[{0}]={1},", item.Key, paramKey);
                command.Parameters.Add(new System.Data.SqlClient.SqlParameter(paramKey, item.Value));
            }
            foreach (var item in paramters)
            {
                command.Parameters.Add(new System.Data.SqlClient.SqlParameter("@" + item.Key, item.Value));
            }
            fieldsBuilder.TrimEnd();
            sqlBuilder.AppendFormat("UPDATE [{0}] SET {1} WHERE {2}", tableName, fieldsBuilder, condition);

            command.CommandText = sqlBuilder.ToString();
            command.ExecuteNonQuery();
        }

        bool IPersistentBuilder.IsValid
        {
            get { return !String.IsNullOrEmpty(tableName) && paramters.Count > 0; }
        }
    }
}
